package dao

import (
	"context"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"time"
)

type ArticleReaderDAO interface {
	// Upsert INSERT OR UPDATE 语义，一般简写为 Upsert
	// 将会更新标题和内容，但是不会更新别的内容，用于同库不同表
	Upsert(ctx context.Context, art PublishedArticle) error
}
type GormArticleReaderDAO struct {
	db *gorm.DB
}

func NewGormArticleReaderDAO(db *gorm.DB) ArticleReaderDAO {
	return &GormArticleReaderDAO{db: db}
}
func (g *GormArticleReaderDAO) Upsert(ctx context.Context, art PublishedArticle) error {
	now := time.Now().UnixMilli()
	art.Ctime = now
	art.Utime = now
	return g.db.WithContext(ctx).Clauses(clause.OnConflict{
		//二选一
		//DoNothing:
		//mysql只需要关心这里
		DoUpdates: clause.Assignments(map[string]interface{}{
			"title":   art.Title,
			"content": art.Content,
			"utime":   now,
			"status":  art.Status,
		}),
	}).Create(&art).Error
	//插入或在冲突时更新记录
}
